Skip to content

MkImage

Show source on GitHub

Image including optional caption.

Example: With caption

Jinja

{{ "https://picsum.photos/200" | MkImage(caption="A caption!") }}

Python

MkImage('https://picsum.photos/200', caption='A caption!')

A caption!

<figure markdown>
  ![](https://picsum.photos/200)
  <figcaption>A caption!</figcaption>
</figure>
<figure>
<p><img alt="" src="https://picsum.photos/200">
  </p>
<figcaption>A caption!</figcaption>
</figure>
.. image:: https://picsum.photos/200
    :alt: A caption!
<picture>
 <img alt="A caption!" src="https://picsum.photos/200">
</picture>

Example: Right-aligned

Jinja

{{ "https://picsum.photos/200" | MkImage(align="right") }}

Python

MkImage('https://picsum.photos/200', align='right')

![](https://picsum.photos/200){ align=right }
<p><img align="right" alt="" src="https://picsum.photos/200"></p>
.. image:: https://picsum.photos/200
    :align: right
<picture>
 <img alt="" src="https://picsum.photos/200">
</picture>

Example: Fixed width

Jinja

{{ "https://picsum.photos/200" | MkImage(width=500) }}

Python

MkImage('https://picsum.photos/200', width=500)

![](https://picsum.photos/200){ width="500" }
<p><img alt="" src="https://picsum.photos/200" width="500"></p>
.. image:: https://picsum.photos/200
    :width: 500
<picture>
 <img alt="" src="https://picsum.photos/200">
</picture>

Example: Hyperlinked

Jinja

{{ "https://picsum.photos/200" | MkImage(target="https://phil65.github.io/mknodes") }}

Python

MkImage('https://picsum.photos/200', target='https://phil65.github.io/mknodes')

[![](https://picsum.photos/200)](https://phil65.github.io/mknodes)
<p><a href="https://phil65.github.io/mknodes"><img alt="" src="https://picsum.photos/200"></a></p>
.. image:: https://picsum.photos/200
    :target: https://phil65.github.io/mknodes
<picture>
 <img alt="" src="https://picsum.photos/200">
</picture>

Example: Separate dark mode image

Jinja

{{ "https://picsum.photos/200" | MkImage(path_dark_mode="https://picsum.photos/300") }}

Python

MkImage('https://picsum.photos/200', path_dark_mode='https://picsum.photos/300')

![](https://picsum.photos/300#only-dark) ![](https://picsum.photos/200#only-light)
<p><img alt="" src="https://picsum.photos/300#only-dark"> <img alt="" src="https://picsum.photos/200#only-light"></p>
.. image:: https://picsum.photos/200
<picture>
 <source media="(prefers-color-scheme: dark)" srcset="https://picsum.photos/300">
 <source media="(prefers-color-scheme: light)" srcset="https://picsum.photos/200">
 <img alt="" src="https://picsum.photos/200">
</picture>

Bases: MkNode

__init__

__init__(
    path: str,
    *,
    target: LinkableType | None = None,
    caption: str = "",
    title: str = "",
    align: Literal["left", "right"] | None = None,
    width: int | None = None,
    lazy: bool = False,
    path_dark_mode: str | None = None,
    **kwargs: Any
)

Parameters:

Name Type Description Default
path str

path of the image

required
target LinkableType | None

Optional URL or node the image should link to

None
caption str

Image caption

''
title str

Image title

''
align Literal['left', 'right'] | None

Image alignment

None
width int | None

Image width in pixels

None
lazy bool

Whether to lazy-load image

False
path_dark_mode str | None

Optional alternative image for dark mode

None
kwargs Any

Keyword arguments passed to parent

{}
Name Children Inherits
MkBinaryImage
mknodes.basenodes.mkbinaryimage
Image carrying the data by itself.
    MkBadge
    mknodes.templatenodes.mkbadge
    Node for a locally-created badge (based on "anybadge").
      Name Children Inherits
      MkNode
      mknodes.basenodes.mknode
      Base class for everything which can be expressed as Markup.
      graph TD
        94721307729824["mkimage.MkImage"]
        94721308848336["mknode.MkNode"]
        94721311766592["node.Node"]
        140564252373184["builtins.object"]
        94721308848336 --> 94721307729824
        94721311766592 --> 94721308848336
        140564252373184 --> 94721311766592
      /home/runner/work/mknodes/mknodes/mknodes/basenodes/mkimage/metadata.toml
      [metadata]
      icon = "mdi:image"
      name = "MkImage"
      group = "image"
      
      [examples.with_caption]
      title = "With caption"
      jinja = """
      {{ "https://picsum.photos/200" | MkImage(caption="A caption!") }}
      """
      
      [examples.right_aligned]
      title = "Right-aligned"
      jinja = """
      {{ "https://picsum.photos/200" | MkImage(align="right") }}
      """
      
      [examples.fixed_width]
      title = "Fixed width"
      jinja = """
      {{ "https://picsum.photos/200" | MkImage(width=500) }}
      """
      
      [examples.hyperlinked]
      title = "Hyperlinked"
      jinja = """
      {{ "https://picsum.photos/200" | MkImage(target="https://phil65.github.io/mknodes") }}
      """
      
      [examples.dark_mode_image]
      title = "Separate dark mode image"
      jinja = """
      {{ "https://picsum.photos/200" | MkImage(path_dark_mode="https://picsum.photos/300") }}
      """
      
      [fragments]
      image = """
      ![{{ node.title ~ "](" ~ path ~ (mode | add("#only-")) ~ ")" ~ (node.align | add("{ align=", " }")) ~ (node.width | add('{ width="', '" }')) }}{% if node.lazy %}{ loading=lazy }{% endif %}
      """
      linked_image = """
      {% if node.url %}
      [{{ "fragments/image" | render_template(node=node, path=path, mode=mode) }}]({{ node.url }}){% else %}
      {{ "fragments/image" | render_template(node=node, path=path, mode=mode) }}{% endif %}
      """
      
      [output.markdown]
      template = """
      {% if node.path_dark_mode %}
      {% set link_dark = "fragments/linked_image" | render_template(node=node, path=node.path_dark_mode, mode="dark") %}
      {% set link_light = "fragments/linked_image" | render_template(node=node, path=node.path, mode="light") %}
      {% set markdown_link = link_dark ~ " " ~ link_light %}
      {% else %}
      {% set markdown_link = "fragments/linked_image" | render_template(node=node, path=node.path, mode=None) %}
      {% endif %}
      {% if node.caption %}
      <figure markdown>
        {{ markdown_link }}
        <figcaption>{{ node.caption }}</figcaption>
      </figure>
      {% else %}
      {{ markdown_link }}{% endif %}
      """
      
      [output.github]
      template = """
      <picture>
      {% if node.path_dark_mode %}
       <source media="(prefers-color-scheme: dark)" srcset="{{ node.path_dark_mode }}">
       <source media="(prefers-color-scheme: light)" srcset="{{ node.path }}">
      {% endif %}
       <img alt="{{ node.caption }}" src="{{ node.path }}">
      </picture>
      """
      
      [output.rst]
      template = """
      .. image:: {{ node.path }}
      {% if node.width %}    :width: {{ node.width }}{% endif %}
      {% if node.caption %}    :alt: {{ node.caption }}{% endif %}
      {% if node.align %}    :align: {{ node.align }}{% endif %}
      {% if node.url %}    :target: {{ node.url }}{% endif %}
      """
      
      mknodes.basenodes.mkimage.MkImage
      class MkImage(mknode.MkNode):
          """Image including optional caption."""
      
          ICON = "material/image"
          ATTR_LIST_SEPARATOR = ""
      
          def __init__(
              self,
              path: str,
              *,
              target: linkprovider.LinkableType | None = None,
              caption: str = "",
              title: str = "",
              align: Literal["left", "right"] | None = None,
              width: int | None = None,
              lazy: bool = False,
              path_dark_mode: str | None = None,
              **kwargs: Any,
          ):
              """Constructor.
      
              Args:
                  path: path of the image
                  target: Optional URL or node the image should link to
                  caption: Image caption
                  title: Image title
                  align: Image alignment
                  width: Image width in pixels
                  lazy: Whether to lazy-load image
                  path_dark_mode: Optional alternative image for dark mode
                  kwargs: Keyword arguments passed to parent
              """
              super().__init__(**kwargs)
              self.title = title
              self.caption = caption
              self.target = target
              self.align = align
              self.width = width
              self.lazy = lazy
              self._path_dark_mode = path_dark_mode
              self._path = path
      
          @property
          def path(self) -> str:
              if helpers.is_url(self._path):
                  return self._path
              # TODO: linkreplacer doesnt work yet with full path
              return pathlib.Path(self._path).name  # this should not be needed.
      
          @property
          def path_dark_mode(self):
              match self._path_dark_mode:
                  case str() if helpers.is_url(self._path_dark_mode):
                      return self._path_dark_mode
                  case str():
                      return pathlib.Path(self._path_dark_mode).name
                  case _:
                      return None
      
          @property
          def url(self) -> str:
              return self.ctx.links.get_url(self.target) if self.target else ""
      
          def _to_markdown(self) -> str:
              if not self.path_dark_mode:
                  markdown_link = self._build(self.path)
              else:
                  link_2 = self._build(self.path, "light")
                  link_1 = self._build(self.path_dark_mode, "dark")
                  markdown_link = f"{link_1} {link_2}"
              if not self.caption:
                  return markdown_link
              lines = [
                  "<figure markdown>",
                  f"  {markdown_link}",
                  f"  <figcaption>{self.caption}</figcaption>",
                  "</figure>",
              ]
              return "\n".join(lines) + "\n"
      
          def _build(self, path, mode: Literal["light", "dark"] | None = None) -> str:
              if mode:
                  path += f"#only-{mode}"
              markdown_link = f"![{self.title}]({path})"
              if self.align:
                  markdown_link += f"{{ align={self.align} }}"
              if self.width:
                  markdown_link += f'{{ width="{self.width}" }}'
              if self.lazy:
                  markdown_link += "{ loading=lazy }"
              if self.target:
                  markdown_link = f"[{markdown_link}]({self.url})"
              return markdown_link